# -* - coding: UTF-8 -* -
import logging 
#reload(sys)
#sys.setdefaultencoding('utf8')
from driver import QueueDriver
import pika
#队列驱动抽像类
class RabbitmqQueue(QueueDriver):  
	def create(self):  
		self.queue_host = self.config.get('queue_server','host','localhost')
		self.queue_port = self.config.get_int('queue_server','port',5672)
		self.queue_user = self.config.get('queue_server','user','guest')
		self.queue_pass = self.config.get('queue_server','pass','guest')
		#self.queue_name = queue_nameself.config.get('queue_server','name','default')
		self.prefetch_count = self.config.get_int('queue_server','prefetch_count',0)
		self.queue_capacity = self.config.get_int('queue_server','capacity',0)
		host_list = self.queue_host.split(',')   #HA中有多个rabbit主机
		for host in host_list: #依次链接rabbit，知道链接成功
			try:
				self.connection = pika.BlockingConnection(pika.ConnectionParameters(
															host=host,
															port=self.queue_port,
															credentials=pika.PlainCredentials(
																username=self.queue_user, 
																password=self.queue_pass)))
				break
			except Exception as e:
				#logger.error("connect rabbitmq failed: %s" % e)
				 pass
		#交换机名
		exchange_name = self.queue_name+'_exchange'
		#队列名
		queue_name = self.queue_name+'_queue'
		#路由名
		route_name = self.queue_name+'_key'
		
		self.channel = self.connection.channel()
		
		#随机建立一个queue，为了监听返回的结果
		self.channel.exchange_declare(
			exchange=exchange_name,
			exchange_type='x-delayed-message',
			durable=True,
			arguments={"x-delayed-type": "fanout"}
		)
		if self.queue_capacity>0:
			try:
				self.channel.queue_declare(queue=queue_name, durable=True, arguments={'x-max-length': self.queue_capacity})
			except Exception as e:
				self.channel.queue_declare(queue=queue_name, durable=True)
				logging.exception(e)
		else:
			self.channel.queue_declare(queue=queue_name, durable=True)
		
		self.channel.queue_bind(exchange=exchange_name, queue=queue_name, routing_key=route_name)
		
		if self.prefetch_count>0:
			self.channel.basic_qos(prefetch_count=self.prefetch_count)
		#logging.error(self.queue_name)
	def listen(self,on_request):
		try:
			self.create()
			if self.channel:
				self.channel.basic_consume(on_request,queue=self.queue_name+'_queue',no_ack=True)#		
				self.channel.start_consuming()
				return True
			else:
				return False
		except Exception as e:
			logging.exception(e)
	def send(self,body,args={}):
		if self.channel:
			self.channel.basic_publish(exchange=self.queue_name+'_exchange',routing_key=self.queue_name+'_key',body=body)
			return True
		else:
			return False			
	def stop(self):
		if self.channel:
			self.channel.stop_consuming()
			return True
		else:
			return False
 